package com.zg.autoflow.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zg.autoflow.req.SettleWorkflowStepUserReq;
import com.zg.autoflow.service.SettleWorkflowStepService;
import com.zg.autoflow.service.SettleWorkflowStepSubService;
import com.zg.autoflow.service.SettleWorkflowStepUserService;
import com.zg.common.core.dao.autoflow.dao.*;
import com.zg.common.core.dao.autoflow.entity.*;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author zg
*/
@Service
@RequiredArgsConstructor
public class SettleWorkflowStepUserServiceImpl implements SettleWorkflowStepUserService {

    private final SettleWorkflowStepSubService settleWorkflowStepSubService;
    private final SettleWorkflowInstanceDao settleWorkflowInstanceDao;
    private final SettleWorkflowStepUserDao settleWorkflowStepUserDao;
    private final SettleWorkflowStepSubUserDao settleWorkflowStepSubUserDao;

    @Override
    public List<String> getNextStepUserList(SettleWorkflowStepUserReq settleWorkflowStepUserReq) {
        SettleWorkflowInstance settleWorkflowInstance = settleWorkflowInstanceDao.getOne(new LambdaQueryWrapper<SettleWorkflowInstance>().eq(SettleWorkflowInstance::getInstCode, settleWorkflowStepUserReq.getInstCode()));
        SettleWorkflowStepSub settleWorkflowStepSub = settleWorkflowStepSubService.getCurSubFlowStepSub(settleWorkflowInstance, settleWorkflowStepUserReq.getStepCode());
        if (settleWorkflowStepSub != null) {
            //走子流程
            List<SettleWorkflowStepSubUser> settleWorkflowStepSubUserList =  settleWorkflowStepSubUserDao.list(new LambdaQueryWrapper<SettleWorkflowStepSubUser>().eq(SettleWorkflowStepSubUser::getSubFlowId, settleWorkflowStepSub.getId()).eq(SettleWorkflowStepSubUser::getStepCode, settleWorkflowStepUserReq.getStepCode()));
            if (settleWorkflowStepSubUserList != null && !settleWorkflowStepSubUserList.isEmpty()) {
                return settleWorkflowStepSubUserList.stream()
                        .map(user -> user.getStepHandler().toString())
                        .collect(Collectors.toList());
            }
        } else {
            //走主流程
            List<SettleWorkflowStepUser> settleWorkflowStepUsers = settleWorkflowStepUserDao.list(new LambdaQueryWrapper<SettleWorkflowStepUser>().eq(SettleWorkflowStepUser::getFlowCode, settleWorkflowInstance.getFlowCode()).eq(SettleWorkflowStepUser::getStepCode, settleWorkflowStepUserReq.getStepCode()));
            if (settleWorkflowStepUsers != null && !settleWorkflowStepUsers.isEmpty()) {
                return settleWorkflowStepUsers.stream()
                        .map(SettleWorkflowStepUser::getOperUser)
                        .collect(Collectors.toList());
            }
        }

        return Collections.emptyList();
    }
}
